package com.hmdp.config;


import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

@Aspect
@Component
@Slf4j
public class RequestLoggingAspect {
        @Around("@annotation(com.hmdp.config.LogRequest)")
        public Object logRequest(ProceedingJoinPoint joinPoint) throws Throwable {
            // 获取当前请求
            HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();

            // 记录请求信息
            String requestURL = request.getRequestURL().toString();
            String httpMethod = request.getMethod();
            String ip = request.getRemoteAddr();
            String className = joinPoint.getSignature().getDeclaringTypeName();
            String methodName = joinPoint.getSignature().getName();

             //执行方法，并记录执行时间，around通知才需要写执行原本方法的代码
            LocalDateTime now= LocalDateTime.now();
            String startTime = now.format(DateTimeFormatter.ofPattern("yyyy-MM-dd :hh:mm:ss"));
            Object result = joinPoint.proceed();


            // 打印请求日志
            String logMessage = String.format("Request: %s %s, 请求者的IP地址: %s, Class: %s, 请求的方法: %s ,请求的时间: %s",
                    httpMethod, requestURL, ip, className, methodName,startTime);
            log.info(logMessage);

            return result;
        }
    }


